package com.lzc;

import java.sql.*;

public class DBUtil {
    //    静态块，在当前类被加载时执行,优先级高于main
    static {
        try {
            //利用驱动工具来注册驱动
            DriverManager.registerDriver(new com.mysql.jdbc.Driver()    );
        } catch (Exception e) {
            System.out.println("数据库驱动加载异常");
        }
    }

    //2.获取数据库连接
    //jdbc:mysql://127.0.0.1:3306/estoredbs?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    private final static String url = "jdbc:mysql://121.196.166.117:3306/estoredbs?useSSL=false";
    private final static String username = "root";
    private final static String password = "jisuanji2022";
    public static Connection getConnection() {
//        2.获取数据连接
        Connection conn = null;
        try{
            conn = DriverManager.getConnection(url, username, password);
        } catch(Exception e){
            e.printStackTrace();
            System.out.println("数据库连接异常");
        }
        return conn;
    }
    //       关闭资源
    public static void closeResource(Connection conn, Statement stmt, ResultSet rs) {
        //4.关闭结果集
        try {
            if (rs != null) {
                if (!rs.isClosed()) {
                    rs.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //关闭操作对象
        try {
            if (stmt != null) {
                if (!stmt.isClosed()) {
                    stmt.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        关闭连接
        try {
            if (conn != null) {
                if (!conn.isClosed()) {
                    conn.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


